package bb.lanxing.devicelist

import android.app.Application
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings;
import bb.lanxing.App
import bb.lanxing.R
import bb.lanxing.activity.base.BaseActivity
import bb.lanxing.devices.utils.DeviceServiceChecker
import bb.lanxing.devices.utils.XZDeviceHelper
import bb.lanxing.lib.devices.api.SmartDevice
import bb.lanxing.model.database.Device
import bb.lanxing.mvvm.base.viewmodel.BaseViewModel
import bb.lanxing.util.RxPermissionUtil
import bb.lanxing.util.RxPermissionUtil.PermissionCallBack
import bb.lanxing.util.SensorEnableUtil
import bb.lanxing.util.text.ToastHelper
import bb.lanxing.view.BiciAlertDialogBuilder
import kotlin.jvm.internal.Intrinsics

class XZDeviceListViewModel(application: Application) : BaseViewModel(application) {
    fun isFGBikeComputer(deviceType: Int): Boolean {
        var vRet = false
        if (deviceType == SmartDevice.TYPE_WINGS || deviceType == SmartDevice.TYPE_IGPS
            || deviceType == SmartDevice.TYPE_XOSS_G || deviceType == SmartDevice.TYPE_CYCLE_PLUS_M2
            || deviceType == SmartDevice.TYPE_CHILEAF_600 || deviceType == SmartDevice.TYPE_CYCLE_PLUS_M1) {
            vRet = true
        }
        return vRet
    }

    fun checkPermission(activity: BaseActivity, permissionGrantCallBack: () -> Unit) {
        val bluetoothPermissions = RxPermissionUtil.getBluetoothPermissions()
        if (RxPermissionUtil.getInstance().checkPermission(
                activity, *bluetoothPermissions.copyOf(bluetoothPermissions.size)
            )
        ) {
            val result = checkBlueToothEnable(activity)
            if (result) {
                checkLocationServiceIfNeedOpen(permissionGrantCallBack)
            }
            return
        }
        showPermissionDialog(activity, permissionGrantCallBack)
    }

    private fun showPermissionDialog(activity: BaseActivity, callBack: () -> Unit) {
        val create =
            BiciAlertDialogBuilder(activity).setTitle(activity.getString(R.string.permission_request_permission_tips))
                .setCancelable(true).setPositiveButton(R.string.dialog_btn_ok) { _, _ ->
                    requestPermission(
                        activity, callBack
                    )
                }.setNegativeButton(R.string.skip) { dialog, which ->
                    //todo:1
                }.create()
        //        }).setNegativeButton(R.string.skip, XZDeviceListViewModel$$ExternalSyntheticLambda1.INSTANCE).create();
        if (Build.VERSION.SDK_INT >= 31) {
            create.setMessage(
                activity.getResources()
                    .getString(R.string.permission_smart_device_need_storage_and_bluetooth)
            )
        } else {
            create.setMessage(
                activity.getResources()
                    .getString(R.string.permission_smart_device_need_storage_and_loc)
            )
        }
        create.show()
    }

    /**
     * @return true(已经打开), false(不支持,或者没有打开)
     */
    fun checkBlueToothEnable(activity: BaseActivity): Boolean {
        val defaultAdapter = BluetoothAdapter.getDefaultAdapter()
        if (defaultAdapter == null) {
            ToastHelper.toastLong(
                App.getContext(),
                App.getContext().getString(R.string.device_bluetooth_not_supported)
            )
            return false
        } else if (defaultAdapter.isEnabled) {
            startDeviceServiceIfNeed()
            return true
        } else {
            SensorEnableUtil.requestEnableBluetooth(activity)
            return false
        }
    }

    fun checkLocationServiceIfNeedOpen(permissionGrantCallBack: () -> Unit) {
        if (Build.VERSION.SDK_INT < 31 || RxPermissionUtil.isHarmonyOs()) {
            if (RxPermissionUtil.isOpenLocService(App.getContext())) {
                permissionGrantCallBack.invoke()
                return
            }
            ToastHelper.toastLong(
                App.getContext(), App.getContext().getString(R.string.st_need_request_location)
            )
            val context = App.getContext()
            gotoLocServiceSettings(context)
            return
        }
        permissionGrantCallBack.invoke()
    }

    private fun requestPermission(activity: BaseActivity, callBack: () -> Unit) {
        val rxPermissionUtil = RxPermissionUtil.getInstance()
        val bluetoothPermissions = RxPermissionUtil.getBluetoothPermissions()
        rxPermissionUtil.setPermissions(*bluetoothPermissions.copyOf(bluetoothPermissions.size))
            .permissionRequestEachCombined(activity, object : PermissionCallBack {
                override fun granted() {
                    if (!App.isManagersInit) {
                        App.getContext().initManagersWithPermissions()
                    }
                    val result = checkBlueToothEnable(activity)
                    if (result) {
                        checkLocationServiceIfNeedOpen(callBack)
                    }
                }

                override fun deny() {
                    ToastHelper.toastLong(
                        App.getContext(), App.getContext().getString(R.string.permission_basic)
                    )
                }
            })
    }

    private fun startDeviceServiceIfNeed() {
        if (!DeviceServiceChecker.getInstance().isDeviceServiceStart) {
            DeviceServiceChecker.getInstance().startDeviceServiceAndAutoConnector()
        }
    }

    fun isConnected(i: Int): Boolean {
        val deviceManager = XZDeviceHelper.getDeviceManager()
        return deviceManager != null && deviceManager.isConnected(i)
    }

    val boundedSensorDevices: List<SmartDevice>
        get() {
            var devicesByLogicType = Device.getDevicesByLogicType(SmartDevice.TYPE_SENSORS)
            if (devicesByLogicType == null) {
                devicesByLogicType = emptyList()
            }
            return devicesByLogicType
        }
    val boundedComputerDevices: List<SmartDevice>
        get() {
            var devicesByLogicType = Device.getDevicesByLogicType(SmartDevice.TYPE_BIKE_COMPUTER)
            if (devicesByLogicType == null) {
                devicesByLogicType = emptyList()
            }
            return ArrayList(devicesByLogicType)
        }

    private fun gotoLocServiceSettings(context: Context) {
        Intrinsics.checkNotNullParameter(context, "context")
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }
}